package com.vm;
import com.vm.R;
import com.vm.LoginActivity;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

 
public class LoginActivity extends Activity {
	
	private SQLiteDatabase db;
	
	DataBaseHelperSqlFromFile myDbHelper;
	 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		try{
	    	super.onCreate(savedInstanceState);
	        setContentView(R.layout.login);
	        
	        myDbHelper = new DataBaseHelperSqlFromFile(this);
	        myDbHelper.createDataBase(this);
	        
	        final EditText txtUserName = (EditText)findViewById(R.id.editText1);
			final EditText txtPassword = (EditText)findViewById(R.id.editText2);
			Button btnLogin = (Button)findViewById(R.id.button1);
			btnLogin.setOnClickListener(new OnClickListener(){

				//@Override
				public void onClick(View v) {
					String username = txtUserName.getText().toString();
					String password = txtPassword.getText().toString();
					try{
						if(username.length() > 0 && password.length() >0)
						{																					
							db = myDbHelper.getWritableDatabase();
							
							if(Login(username, password))
							{
								Toast.makeText(LoginActivity.this,"Logeo Satisfactorio", Toast.LENGTH_LONG).show();
								Intent intent = new Intent(LoginActivity.this, frmPpal.class);
					            startActivity(intent);
							}else{
								Toast.makeText(LoginActivity.this,"Usuario o Clave Invalida", Toast.LENGTH_LONG).show();
							}							
						}
						
					}catch(Exception e)
					{
						Toast.makeText(LoginActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
					}
				}
				
			});
	        
		} catch (IOException ioe) {
	 		throw new Error("Error al crear base de datos");
	 	}
	}
	
	public boolean Login(String USUARIO, String CLAVE) throws SQLException
    {
    	Cursor mCursor = db.rawQuery("SELECT * FROM VMUSUARIOS WHERE USUARIO=? AND CLAVE=?", new String[]{USUARIO,CLAVE});
        if (mCursor != null) {           
            if(mCursor.getCount() > 0)
            {
            	return true;
            }
        }
     return false;
    }
	
}





